//
//  FlutterPluginDemoTextView.swift
//  ivy_ezviz_plugin
//
//  Created by 崔兴瑞 on 2020/12/29.
//

import Foundation


class EzvizUIKitView: NSObject, FlutterPlatformView, EZUIPlayerDelegate, FlutterPlugin,FlutterStreamHandler {
    
    
    
    
    let frame: CGRect
    let viewId: Int64
    let mPlayer: EZUIPlayer
    let uiView: UIView
    let _channel:FlutterMethodChannel
    private var eventSink: FlutterEventSink? = nil
    
    static func register(with registrar: FlutterPluginRegistrar) {
    }
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        print("com.ivy.ezviz.uikit.event_ onCancel\n")
        return nil
    }
    init(_ frame: CGRect, viewId: Int64, args: Any?,registrar:FlutterPluginRegistrar) {
        self.frame = frame
        self.viewId = viewId
        
        let dict = args as! NSDictionary
        let AppKey = dict.value(forKey: "AppKey") as! String
        let accessToken = dict.value(forKey: "accessToken") as! String
        let playUrl = dict.value(forKey: "playUrl") as! String

        EZUIKit.initWithAppKey(AppKey)
        EZUIKit.setAccessToken(accessToken)
        self.mPlayer = EZUIPlayer.createPlayer(withUrl: playUrl)
        
        self.uiView = mPlayer.previewView
        //播放
        self.mPlayer.startPlay()
        //注册方法
        _channel = FlutterMethodChannel(name: "ivy_ezviz_plugin_"+String(viewId), binaryMessenger: registrar.messenger())
        
        //监听
        let eventChannel = FlutterEventChannel(name: "com.ivy.ezviz.uikit.event_"+String(viewId), binaryMessenger: registrar.messenger())
        super.init()
        eventChannel.setStreamHandler(self)
        registrar.addMethodCallDelegate(self, channel: _channel)
        
        self.mPlayer.mDelegate = self
        //播放
        self.mPlayer.startPlay()
        
        
        
    }
    

    func view() -> UIView {
        self.uiView
    }
    func dispose(){
        self.mPlayer.release()
    }
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
//      result("iOS " + UIDevice.current.systemVersion)
        
        if(call.method == "ezviz.getStatus"){
            /**
            * 获取当前状态：
            * EZUIPlayer.STATUS_INIT = 0;
            * EZUIPlayer.STATUS_START = 1;
            * EZUIPlayer.STATUS_STOP = 2;
            * EZUIPlayer.STATUS_PLAY = 3;
            * EZUIPlayer.STATUS_PAUSE = 4;
            * @return
            */
            //var status = getStatus()
            result(["status" :"ios暂不支持"])

        }else if(call.method == "ezviz.releasePlayer"){
            //释放资源
            releasePlayer()
            result(["releasePlayer" :"success"])
        }else if (call.method == "ezviz.startPlay") {
            //播放
            startPlay()
            result(["startPlay" :"success"])
        }else if (call.method == "ezviz.stopPlay") {
            //停止
            stopPlay()
            result(["stopPlay" :"success"])
        }else if (call.method == "ezviz.setUrl") {
            let arguments = call.arguments as! [String: Any]
            let url:String = arguments["url"] as! String
            //设置播放的url
            setUrl(url: url)
            result(["setUrl" :"success"])
        }else if (call.method == "ezviz.pausePlay") {
            //暂停播放，回放专用接口
            pausePlay()
            result(["pausePlay" :"success"])
        }else if (call.method == "ezviz.resumePlay") {
            //恢复播放，回放专用接口
            resumePlay()
            result(["resumePlay" :"success"])
        }else if (call.method == "ezviz.seekPlayback") {
            let arguments = call.arguments as! [String: Any]
            let date:String = arguments["date"] as! String
            //seek播放位置,回放使用
            seekPlayback(date: date)
            result(["seekPlayback" :"success"])
        }else if (call.method == "ezviz.setSurfaceSize") {
            let arguments = call.arguments as! [String: Any]
            let width:Int = arguments["width"] as? Int ?? 10
            let height:Int = arguments["height"] as? Int ?? 10
            //动态设置播放区域大小
            setSurfaceSize(width: width, height: height)
            result(["setSurfaceSize" :"ios暂不支持"])
        }else if (call.method == "ezviz.controlPTZ") {
            let arguments = call.arguments as! [String: Any]

            let deviceSerial:String = arguments["deviceSerial"] as? String ?? ""
            let cameraNo:Int = arguments["cameraNo"] as? Int ?? 1
            let commandStr:String = arguments["command"] as? String ?? ""
            let actionStr:String = arguments["action"] as? String ?? ""
            let speed:Int = arguments["speed"] as? Int ?? 1

            //动态设置播放区域大小
            controlPTZ(deviceSerial: deviceSerial, cameraNo: cameraNo, commandStr: commandStr, actionStr: actionStr, speed: speed)
            result(["controlPTZ" :"success"])
        }else if (call.method == "ezviz.captureCamera") {
            let arguments = call.arguments as! [String: Any]
            let deviceSerial:String = arguments["deviceSerial"] as? String ?? ""
            let cameraNo:Int = arguments["cameraNo"] as? Int ?? 1
            //截图
            captureCamera(deviceSerial: deviceSerial, cameraNo: cameraNo)
            
            result(["setUrl" :"success"])
        } else{
            result(FlutterMethodNotImplemented)
        }
    }
    /**
     * 获取当前状态：
     * EZUIPlayer.STATUS_INIT = 0;
     * EZUIPlayer.STATUS_START = 1;
     * EZUIPlayer.STATUS_STOP = 2;
     * EZUIPlayer.STATUS_PLAY = 3;
     * EZUIPlayer.STATUS_PAUSE = 4;
     * @return
     */
    func getStatus()-> Int {
        //var status = self.mPlayer.status
        //return status
        return 0;
    }
    /**
     * 释放资源
     */
    func releasePlayer() {
        self.mPlayer.release()
    }
    /**
     * 播放
     */
    func startPlay() {
        self.mPlayer.startPlay()
    }

    /**
     * 停止
     */
    func stopPlay() {
        self.mPlayer.stopPlay()
    }
    /**
     * 设置播放的url
     */
    func setUrl(url: String) {
        self.mPlayer.release()
        self.mPlayer.setEZOpenUrl(url)
        self.mPlayer.startPlay()
    }
    /**
     * 暂停播放，回放专用接口
     */
    func pausePlay() {
        self.mPlayer.pausePlay()
    }

    /**
     * 恢复播放，回放专用接口
     */
    func resumePlay() {
        self.mPlayer.resumePlay()
    }
    /**
     * seek播放位置,回放使用
     * var  calendar
     */
    func seekPlayback(date: String) {
        let df = DateFormatter.init()
        df.dateFormat = "yyyy-MM-dd HH:mm"
        let time = df.date(from: date)
        
        self.mPlayer.seek(toTime: time)
    }
    /**
     * 动态设置播放区域大小
     * 当width等于0（height等于0）时，播放区域以height（width）为标准，宽高按视频分辨率比例播放
     *
    var  width  播放区域宽
    var  height 播放区域高
     */
    func setSurfaceSize(width: Int, height: Int) {
        ///暂不支持
    }
    
    /**
     * PTZ 控制接口
     * 该接口为耗时操作，必须在线程中调用
     * var  deviceSerial   设备序列号
     * var  cameraNo        通道号
     * var  command ptz控制命令
     * var  action 控制启动/停止
     * var  speed 速度（0-2）
     * @return 操作成功或者失败(返回失败错误码)
     */
    func controlPTZ(deviceSerial: String, cameraNo: Int, commandStr: String, actionStr: String, speed: Int) {
        var command: EZPTZCommand = EZPTZCommand.up//ptz控制命令
        if (commandStr == "EZPTZCommand.EZPTZCommandUp") {
            command = EZPTZCommand.up//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandDown") {
            command = EZPTZCommand.down//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandLeft") {
            command = EZPTZCommand.left//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandRight") {
            command = EZPTZCommand.right//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandZoomIn") {
            command = EZPTZCommand.zoomIn//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandZoomOut") {
            command = EZPTZCommand.zoomOut//ptz控制命令
        }
        var action: EZPTZAction = EZPTZAction.start //控制启动/停止
        if (actionStr == "EZPTZAction.EZPTZActionSTART") {
            action = EZPTZAction.start;
        } else if (actionStr == "EZPTZAction.EZPTZActionSTOP") {
            action = EZPTZAction.stop;
        }
        EZOpenSDK.controlPTZ(deviceSerial,cameraNo: cameraNo,command: command,action: action,speed: speed, result: {(error)->Void in self.errorBack(e: error as Any)})


    }
    //控制报错
    func errorBack(e : Any){
        
        let error :NSError? = (e as? NSError)
        if((error?.localizedDescription) != nil){
            eventSink?(["type":"controlPTZ","msg": error?.localizedDescription ?? "error","code":500])
        }
        
    }
    /**
     * 截图
     */
    func captureCamera(deviceSerial: String, cameraNo: Int) {

        EZOpenSDK.captureCamera(deviceSerial, cameraNo: cameraNo, completion:{
            (str,error)->Void in self.captureErrorBack(str: str as Any, e: error as Any)
        } )
        //<#((String?, Error?) -> Void)?#>
        //(str,error)->Void in self.captureErrorBack(str: str as Any,e: error as Any)
    }
    //截图报错
    func captureErrorBack(str :Any,e : Any){
      
        let error :NSError? = (e as? NSError)
        if((error?.localizedDescription) != nil){
            eventSink?(["type":"captureCamera","msg": error?.localizedDescription ?? "error","code":500])
        }else{
            eventSink?(["type":"captureCamera","msg": str,"code":0])
        }
        
    }
}
